package com.wx.service.impl;

import java.awt.image.BufferedImage;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.imageio.ImageIO;

import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.wx.exception.ServiceException;
import com.wx.mapper.CommodityMapper;
import com.wx.mapper.FileMapper;
import com.wx.mapper.UserMapper;
import com.wx.pojo.Commodity;
import com.wx.pojo.User;
import com.wx.service.FileService;

@Service
public class FileServiceImpl implements FileService{

	private String dirPath = "/usr/local/src/imgs/"; //定义本地磁盘路径      E:\jt-upload
	//private String dirPath = "E://jt-upload/"; //定义本地磁盘路径      /usr/local/src/imgs
	private String urlPath = "http://wx.heyclock.com/";	  //定义虚拟磁盘路径
	//private String urlPath = "120.27.112.29:8090/";	  //定义虚拟磁盘路径

	@Autowired
	private FileMapper fileMapper;

	@Autowired
	private CommodityMapper commodityMapper;

	@Autowired
	private UserMapper userMapper;

	/**
	 * 编程:永远不要相信前台传递的数据
	 * 1.判断是否为图片 jpg|png|gif....
	 * 2.判断是否为恶意程序.
	 * 3.为了方便图片读取,一般分文件存储.
	 * 	 3.1 hash值 8位一截
	 * 	 3.2  时间分割  yyyy/MM/dd
	 * 4.应该防止图片重名 UUID
	 */
	
	@Override
	public Commodity uploadFile(MultipartFile uploadFile,String token) {
		//验证token
		if(token==null) new ServiceException("token 不能为空"); 
		//从数据库查询该token
		User user = userMapper.findUserByToken(token);
		//判断有效性
		if (user==null||!user.getToken().equals(token)) throw new ServiceException("身份信息无效,请登录!");

		//上传操作
		//1.获取图片信息  abc.jpg
		String fileName = uploadFile.getOriginalFilename();
		//2.将字符全部小写.
		fileName = fileName.toLowerCase();
		//3.判断是否为图片类型
		if(!fileName.matches("^.+\\.(jpg|png|gif)$")) {
			//表示不是图片类型
			throw new ServiceException("不是图片类型的文件");
		}
		/**
		 * 4.判断文件是否为恶意程序
		 */
		try {
			BufferedImage image = 
					ImageIO.read(uploadFile.getInputStream());
			int height = image.getHeight();
			int width  = image.getWidth();
			if(height==0 || width==0) {
				throw new ServiceException("....");
			}
			//3.文件存储 yyyy/MM/dd
			String datePath = new SimpleDateFormat("yyyy/MM/dd")
					.format(new Date());
			//3.1创建文件夹
			File dirFile = new File(dirPath+datePath);
			if(!dirFile.exists()) {
				//如果文件不存在,则创建文件夹
				dirFile.mkdirs();
			}
			//3.2为文件生成唯一名称 UUID+后缀
			String uuid = UUID.randomUUID()
					.toString()
					.replace("-","");
			//图片名称  abc.jpg  截串的规则:包头不包尾
			String fileType = 
					fileName.substring(fileName.lastIndexOf("."));
			String realFileName = uuid + fileType;

			//4.将文件实现上传  E:/jt-upload/yyyy/MM/dd/UUID.jpg
			File realFile = new File(dirPath+datePath+"/"+realFileName);
			uploadFile.transferTo(realFile);

			//将图片的虚拟路径存入数据库中
			String imgURL = urlPath+datePath+"/"+realFileName;
			//将图片url添加到图片表中
			fileMapper.addImg(imgURL, user.getId());

			//为该图片创建一个商品记录
			Commodity commodity = new Commodity();
			commodity.setImg(imgURL);
			commodity.setUserId(user.getId());
			commodityMapper.insert(commodity);

			return commodity;
		} catch (Exception e) {
			e.printStackTrace();
			throw new ServiceException("系统错误，上传失败！");
		}
	}

	@Override
	public List<Commodity> findImgsByUserId(String token) {
		//验证token
		if(token==null) new ServiceException("token 不能为空"); 
			//从数据库查询该token
		User user = userMapper.findUserByToken(token);
			//判断有效性
		if (user==null||!user.getToken().equals(token)) throw new ServiceException("身份信息无效,请登录!");

		//获取数据
		List<Commodity> list = new ArrayList<>();
		try {
			list =  fileMapper.findImgByUserId(user.getId());
		} catch (Exception e) {
			throw new ServiceException(e);
		}
		//查询数据库
		return list;
	}

	@Override
	public void updateImg(String token,Commodity commodity) {
		//验证token
		if(token==null) new ServiceException("token 不能为空"); 
			//从数据库查询该token
		User user = userMapper.findUserByToken(token);
			//判断有效性
		if (user==null||!user.getToken().equals(token)) throw new ServiceException("身份信息无效,请登录!");
		
		
		//验证commodity
		if(Strings.isEmpty(commodity.getName())||Strings.isEmpty(commodity.getUnit())) throw new IllegalArgumentException("参数不能为空！");
		Commodity comm = fileMapper.findCommodityById(commodity.getId());
		comm.setName(commodity.getName());
		comm.setDes(commodity.getDes());
		comm.setPrice(commodity.getPrice());
		comm.setUnit(commodity.getUnit());
		try {
			commodityMapper.updateById(comm);
		} catch (Exception e) {
			throw new ServiceException(e);
		}
	}

	@Override
	public Commodity findCommodityById(String token, Integer id) {
		//验证token
		if(token==null) new ServiceException("token 不能为空"); 
			//从数据库查询该token
		User user = userMapper.findUserByToken(token);
			//判断有效性
		if (user==null||!user.getToken().equals(token)) throw new ServiceException("身份信息无效,请登录!");
		
		//验证id
		if(id==null) throw new IllegalArgumentException("id不能为空！");
		
		//查询数据
		Commodity commodity = fileMapper.findCommodityById(id);
		return commodity;
	}

}
